﻿using System;
using System.Collections.Generic;
using System.Net.Mqtt;
using System.Text;
using System.Text.RegularExpressions;
using StackExchange.Redis;

namespace AutoAllocService.Messaging
{
    public class MqttHandler
    {
        private readonly IMqttClient _client;
        private readonly Regex _cmdRegex;

        public MqttHandler(IMqttClient client)
        {
            _client = client;
            _cmdRegex = new Regex(@"/CD/TH/Driver/[\d\w]+");
        }

        public void DealMessages(MqttApplicationMessage message)
        {
            var payload = Encoding.UTF8.GetString(message.Payload);

            if (message.Topic == Program.AppSetting.Mqtt.PingTopic)
            {
                HandlerPing(payload);
            }
            else if (_cmdRegex.IsMatch(message.Topic))
            {
                HandlerTask(payload);
            }
        }

        private async void HandlerPing(string code)
        {
            await _client.SubscribeAsync($"/CD/TH/Drivers/{code}", MqttQualityOfService.AtLeastOnce);
        }

        private async void HandlerTask(string json)
        {
            await RedisHelper.Instance.PublishAsync(new RedisChannel("AllocTask", RedisChannel.PatternMode.Auto), json);
        }
    }
}
